<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/*总数字资源（资源商标）model*/

class ResourceBusinessName extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_business_name';


    /**
     *获取资源商名称
     */
    public static function getBusinessName($resource_business_id)
    {
        if (empty($resource_business_id)) {
            return '';
        }
        $resource_business_id = !is_array($resource_business_id) ? explode(',', $resource_business_id) : $resource_business_id;
        $resource_business_id = array_map('intval', $resource_business_id); //强制转换为整型，字符串类型，检索时很慢
        $resource_business_name = self::whereIn('id', $resource_business_id)->where('is_del', 1)->pluck('name')->toArray();
        return $resource_business_name ? join(',', $resource_business_name) : '';
    }

    /**
     *获取列表
     * @param limit int 分页大小
     * @param is_play string 是否发布  1 发布 2 不发布
     * @param keywords string 搜索关键词
     */
    public function lists($search_data = [])
    {
        $keywords = $search_data['keywords'] ?? '';
        $limit = !empty($search_data['limit']) ? $search_data['limit'] : 10;
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];

        $res = $this->select('id', 'name', 'create_time', 'template', 'number as resource_num', 'is_auto_show')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $manage_resource_business_ids = is_array($manage_resource_business_ids) ? $manage_resource_business_ids : explode(',', $manage_resource_business_ids);
                    $manage_resource_business_ids = array_map('intval', $manage_resource_business_ids); //强制转换为整型，字符串类型，检索时很慢
                    $query->whereIn('id', $manage_resource_business_ids);
                }
            })
            ->where('is_del', 1)
            ->orderBy('sort')
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     *获取推荐的书籍数据
     */
    public function getResourceBusinessDataList($big_type_id = null, $limit = 10)
    {
        $res = $this->select('id', 'name', 'create_time', 'template')->where('is_del', 1)->where('id', '<>', 999)->where('is_auto_show', 1)->orderBy('sort')->orderByDesc('id')->limit($limit)->get()->toArray();
        $data = [];
        $i = 0;
        $resourceTotalModel = new ResourceTotal();
        foreach ($res as $key => $val) {
            $resource_total_list = $this->getResourceBusinessDataByBusinessId(null, $val['id'], $big_type_id, null, 1, 8);
            if (!empty($resource_total_list['data'])) {
                // 获取资源数据大类型，分配不同的模版
                if (empty($big_type_id)) {
                    $big_type_id_all = $resourceTotalModel->getBigTypeIdByResourceId($val['id'], $big_type_id);
                } else {
                    $big_type_id_all[] = $big_type_id;
                }
                if (count($big_type_id_all) == 1 && $big_type_id_all[0] == 3) {
                    $val['template'] = 8;
                } elseif (count($big_type_id_all) > 1 && in_array(3, $big_type_id_all)) {
                    $val['template'] = 9;
                } elseif (empty($val['template'])) {
                    $val['template'] = mt_rand(3, 7); //1，2 模版不参与
                }

                foreach ($resource_total_list['data'] as $k => $v) {
                    $resource_total_list['data'][$k]['type_name'] = ResourceTypeExternal::where('id', $v['type_id'])->where('is_del', 1)->value('type_name');
                }

                $val['con_resource_total'] = $resource_total_list['data'];
                $data[$i] = $val;
                $i++;
            }
        }
        return $data;
    }

    /**
     * 根据资源商id获取数据
     * @param resource_business_id  资源商id
     * @param big_type_id  大类id
     * @param type_id  小类id
     * @param keywords 检索数据
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getResourceBusinessDataByBusinessId($keywords, $resource_business_id, $big_type_id = null, $type_id = null, $page = 1, $limit = 10)
    {

        $key = md5('getResourceBusinessDataByBusinessId-' . $keywords . '-' . $resource_business_id . '-' . $big_type_id . '-' . $type_id . '-' . $page . '-' . $limit);
        $res = Cache::get($key);
        if (empty($res)) {
            if ($resource_business_id) {
                $resourceTotalModel = new ResourceTotal();
                $model = $resourceTotalModel->getResourceTotalModel($resource_business_id);
                if (empty($model)) return [];
            } else {
                $model = new ResourceTotal();
            }
            if ($resource_business_id == 3) {
                $sort = 'is_recom ASC,read_sum DESC,id DESC';
            } elseif ($resource_business_id == 4) {
                $sort = 'is_recom ASC,issue_year DESC,id DESC';
            } else {
                $sort = 'is_recom ASC,pre_time DESC,id DESC';
            }

            //获取敏感词
            // $sensitiveWordModel = new SensitiveWord();
            // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
            // DB::enableQueryLog();
            $res = $model->from($model->getTable() . ' as r')
                ->select('r.id', 'r.guid', 'r.resource_business_id', 'r.title', 'r.author', 'r.press', 'r.pre_time', 'r.isbn', 'r.img', 'r.intro', 'r.type_id', 'r.big_type_id', 't.type_name as big_type_name', 'b.name as resource_business_name', 'r.is_recom')
                ->join('resource_type as t', 't.id', '=', 'r.big_type_id')
                ->join('resource_business_name as b', 'b.id', '=', 'r.resource_business_id')
                ->where(function ($query) use ($big_type_id, $type_id) {
                    if ($big_type_id) {
                        $big_type_id = !is_array($big_type_id) ? explode(',', $big_type_id) : $big_type_id;
                        $query->whereIn('r.big_type_id', $big_type_id); //系统大类
                    }
                    if ($type_id) {
                        $type_id = is_array($type_id) ? $type_id : explode(',', $type_id);
                        $type_id = array_map('intval', $type_id); //强制转换为整型，字符串类型，检索时很慢
                        $query->whereIn('r.type_id', $type_id); //系统小类
                    }
                })->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('title', 'like', "%$keywords%")->where('author', 'like', "%$keywords%");
                    }
                })
                ->where(function ($query) use ($resource_business_id) {
                    if ($resource_business_id) {
                        $resource_business_id = !is_array($resource_business_id) ? explode(',', $resource_business_id) : $resource_business_id;
                        $resource_business_id = array_map('intval', $resource_business_id); //强制转换为整型，字符串类型，检索时很慢
                        $query->whereIn('resource_business_id', $resource_business_id);
                    }
                })
                ->where('is_mask', 1)
                ->where('r.is_del', 1)
                ->where('b.is_del', 1)
                ->orderByRaw($sort)
                ->paginate($limit)
                ->toArray();
            Cache::set($key, $res, 5 * 60); //缓存5分钟 
        }
        // dd(DB::getQueryLog());
        return $res;
    }

    /**
     * 重置所有资源商的数量
     */
    public function resetResourceBusinessNameNumber()
    {
        $res = $this->select('id')->where('is_del', 1)->get()->toArray();
        $resourceTotalModel = new ResourceTotal();
        foreach ($res as $val) {
            $number = $resourceTotalModel->getResourceNum($val['id']);     
            $this->where('id', $val['id'])->update(['number' => $number]);
        }
    }
}
